package com.ihighest.app.infox.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.ihighest.app.common.kit.ListViewKit;
import com.ihighest.app.infox.R;

public class QuestionSurveyListAdapter extends BaseAdapter {
	private JSONArray array;
	private Context context;
	private LayoutInflater inflater;
	public static HashMap<String, List<String>> map;
	private int touchedPosition = -1;
	// 定义一个HashMap，用来存放EditText的值，Key是position
	HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
	HashMap<Integer, Boolean> rb = new HashMap<Integer, Boolean>();
	HashMap<Integer, Boolean> cb = new HashMap<Integer, Boolean>();

	public QuestionSurveyListAdapter(Context context) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
	}

	public QuestionSurveyListAdapter(Context context, JSONArray array) {
		this.context = context;
		this.inflater = LayoutInflater.from(context);
		this.array = array;
		System.out.println("array" + array.length());
		map = new HashMap<>();
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return array == null ? 0 : array.length();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position, View contentView, ViewGroup parent) {

		final ViewHolder holder;
		// if (contentView == null) {
		holder = new ViewHolder();
		contentView = inflater.inflate(R.layout.infox_activity_questionsurvey_detailitem, null);
		holder.questionName = (TextView) contentView.findViewById(R.id.questionSurveyDetailItemTitle);
		holder.answerListView = (ListView) contentView.findViewById(R.id.answerListview);
		holder.myAnswer = (EditText) contentView.findViewById(R.id.myAnswerEditText);
		holder.parentLayout = (LinearLayout) contentView.findViewById(R.id.parentLayout);
		contentView.setTag(holder);
		// } else {
		// holder = (ViewHolder) contentView.getTag();
		// }
		holder.parentLayout.removeAllViews();

		try {
			holder.questionName.setText(array.getJSONObject(position).getString("qtitle"));
			String type = array.getJSONObject(position).getString("qtype");
			System.out.println(type);

			if (array.getJSONObject(position).getString("qtype").equals("3")) {
				System.out.println("文本");
				holder.myAnswer.setVisibility(View.GONE);
				holder.answerListView.setVisibility(View.GONE);
				// holder.myAnswer.setVisibility(View.VISIBLE);
				final ArrayList<String> arrayList = new ArrayList<String>();
				// holder.myAnswer.requestFocus();
				// holder.myAnswer.setFocusable(true);
				// holder.myAnswer.setFocusableInTouchMode(true);
				// holder.myAnswer.addTextChangedListener(new TextWatcher() {
				//
				// @Override
				// public void onTextChanged(CharSequence arg0, int arg1, int
				// arg2, int arg3) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void beforeTextChanged(CharSequence arg0, int arg1,
				// int arg2, int arg3) {
				// // TODO Auto-generated method stub
				//
				// }
				//
				// @Override
				// public void afterTextChanged(Editable arg0) {
				// // 将editText中改变的值设置的HashMap中
				// hashMap.put(position, arg0.toString());
				// arrayList.add(holder.myAnswer.getText().toString());
				// try {
				// map.put(array.getJSONObject(position).getString("qid") + "_"
				// +
				// array.getJSONObject(position).getJSONArray("qr").getJSONObject(0).getString("rid"),
				// arrayList);
				// } catch (JSONException e) {
				// // TODO Auto-generated catch block
				// e.printStackTrace();
				// }
				//
				// }
				// });

				EditText answer = new EditText(context);
				answer.setFocusable(true);
				answer.setFocusableInTouchMode(true);
				answer.setPadding(3, 3, 0, 0);
				answer.setBackgroundResource(R.drawable.infox_white_shape_bg);
				answer.setHint("请输入。。。");
				if (touchedPosition == position) {
					answer.requestFocus();
				}
				answer.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View arg0, boolean arg1) {
						touchedPosition = position;

					}
				});
				answer.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
						// TODO Auto-generated method stub

					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable arg0) {
						// 将editText中改变的值设置的HashMap中
						hashMap.put(position, arg0.toString());
						arrayList.add(holder.myAnswer.getText().toString());
						try {
							map.put(array.getJSONObject(position).getString("qid") + "_"
									+ array.getJSONObject(position).getJSONArray("qr").getJSONObject(0).getString("rid"), arrayList);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});

				// 如果hashMap不为空，就设置的editText
				if (hashMap.get(position) != null) {
					answer.setText(hashMap.get(position));
					// holder.myAnswer.setText(hashMap.get(position));
				}
				holder.parentLayout.addView(answer);
			} else if (array.getJSONObject(position).getString("qtype").equals("1")) {
				System.out.println("单选");
				holder.myAnswer.setVisibility(View.GONE);
				holder.answerListView.setVisibility(View.GONE);
				final RadioGroup radioGroup = new RadioGroup(context);

				// 添加单选按钮
				RadioButton radio = null;

				JSONArray singArray = array.getJSONObject(position).getJSONArray("qr");
				for (int i = 0; i < singArray.length(); i++) {
					radio = new RadioButton(context);
					radio.setText(singArray.getJSONObject(i).getString("rtitle"));
					radio.setTag(singArray.getJSONObject(position).getString("rid"));
					radioGroup.addView(radio);

				}
				radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup arg0, int arg1) {
						System.out.println("点击：" + arg1);

						RadioButton tempButton = (RadioButton) arg0.findViewById(arg1); // 通过RadioGroup的findViewById方法，找到ID为checkedID的RadioButton
						try {
							String mqid = array.getJSONObject(position).getString("qid");

							// 以下就可以对这个RadioButton进行处理了
							List<String> answerList = new ArrayList<String>();

							// 如果list中不存在该条数据加入
							System.out.println("加入");
							answerList.add(tempButton.getTag().toString());
							map.put(mqid, answerList);

						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}

				});

				holder.parentLayout.addView(radioGroup);
			} else {
				System.out.println("多选");
				holder.answerListView.setVisibility(View.VISIBLE);
				holder.myAnswer.setVisibility(View.GONE);
				// final String
				// qid=array.getJSONObject(position).getString("qid");
				// JSONArray answerArray =
				// array.getJSONObject(position).getJSONArray("qr");
				// final List<String> mList = new ArrayList<String>();
				// CheckBox cb = null;
				// List<CheckBox> mcb = new ArrayList<CheckBox>();
				// for (int i = 0; i < answerArray.length(); i++) {
				// cb = new CheckBox(context);
				// cb.setText(answerArray.getJSONObject(i).getString("rtitle"));
				// cb.setTag(answerArray.getJSONObject(position).getString("rid"));
				// holder.parentLayout.addView(cb);
				// mcb.add(cb);
				// mcb.get(i).setOnCheckedChangeListener(new
				// CompoundButton.OnCheckedChangeListener() {
				//
				// @Override
				// public void onCheckedChanged(CompoundButton arg0, boolean
				// arg1) {
				// // TODO Auto-generated method stub
				//
				// }
				// });
				// }

				holder.answerListView.setAdapter(new AnswerAdapter(array.getJSONObject(position).getJSONArray("qr"), array.getJSONObject(
						position).getString("qid")));
				ListViewKit.setListViewHeightBasedOnChildren(holder.answerListView);
				// if
				// (array.getJSONObject(position).getString("qtype").equals("1"))
				// {
				// // 如果是单选
				// System.out.println("单选");
				// holder.answerListView.setOnItemClickListener(new
				// OnItemClickListener() {
				// int prePosition = 0;
				//
				// @Override
				// public void onItemClick(AdapterView<?> arg0, View arg1, int
				// arg2, long arg3) {
				// CheckBox cb = (CheckBox)
				// arg1.findViewById(R.id.questionSurveyAnswerItem);
				// cb.setChecked(true);
				//
				// View v = holder.answerListView.getChildAt(prePosition);
				// CheckBox preCb = (CheckBox)
				// v.findViewById(R.id.questionSurveyAnswerItem);
				// preCb.setChecked(false);
				// prePosition = arg2;
				//
				// }
				// });
				// }

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return contentView;
	}

	class ViewHolder {
		TextView questionName;
		ListView answerListView;
		EditText myAnswer;
		LinearLayout parentLayout;
	}

	class AnswerAdapter extends BaseAdapter {
		private JSONArray jsonarray;
		private String id;
		private List<String> answerList;

		public AnswerAdapter(JSONArray array, String id) {
			this.jsonarray = array;
			this.answerList = new ArrayList<String>();
			this.id = id;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return jsonarray == null ? 0 : jsonarray.length();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent) {
			// contentView =
			// inflater.inflate(R.layout.infox_activity_questionsurvey_answeritem,
			// null);
			final CheckBox box = new CheckBox(context);
			try {
				box.setText(jsonarray.getJSONObject(position).getString("rtitle"));
				box.setTag(jsonarray.getJSONObject(position).getString("rid"));
				box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton view, boolean ischeck) {
						if (ischeck) {
							if (!answerList.contains(box.getTag().toString())) {
								// 如果list中不存在该条数据加入
								answerList.add(box.getTag().toString());
								map.put(id, answerList);
							}

						} else {
							if (answerList.contains(box.getTag().toString())) {
								// 如果list中存在该条数据删除
								answerList.remove(box.getTag().toString());
								map.put(id, answerList);
							}
						}
					}
				});
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return box;
		}
	}
}
